﻿/****************
* Authored by Zhuo "Wizcas" Chen
* 2018 © Wubi.fun all rights reserved
*****************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Wubi.Utils;

public class BlockQueue : MonoBehaviour
{
    const int size = 5;
    readonly Vector3 GLOBAL_OFFSET = Vector3.one * 100;
    static BlockQueue _instance;
    public static BlockQueue instance { get { return _instance ?? (_instance = FindObjectOfType<BlockQueue>()); } }

    List<Block> _q = new List<Block>(size);
    static int _spawnCount;

    #region Events
    public System.Action<BlockQueue> onQueueChanged;
    #endregion

    void Start()
    {
        GenToFull();
    }

    public void Enqueue(params string[] ids)
    {
        if (ids == null || ids.Length == 0) return;
        var isDirty = false;
        foreach (var id in ids)
        {
            if (_q.Count >= size) break;;
            var block = Block.Spawn(id);
            if (block == null) break;
            _q.Add(block);
            block.transform.position = GLOBAL_OFFSET * ++_spawnCount;
            isDirty = true;
        }

        if (isDirty && onQueueChanged != null) onQueueChanged(this);
    }

    public void Dequeue(Block block)
    {
        if (_q.Count == 0) return;
        /*var succ = */_q.Remove(block);
        //if (succ && onQueueChanged != null) onQueueChanged(this);

        GenToFull();
    }

    public Block[] Peek()
    {
        Debug.LogFormat("peeking: {0}", _q.Print());
        var ret = new Block[size];
        for(int i =0; i < size;i++)
        {
            if (i >= _q.Count) ret[i] = null;
            else ret[i] = _q[i];
        }
        return ret;
    }

    #region Generating
    public int bThreshold = 5;
    public int higherCountForB = 2;
    public float bChance = .3f;

    public void GenToFull()
    {
        Gen(size - _q.Count);
    }

    public void Regenerate()
    {
        _q.Clear();
        GenToFull();
    }

    public void Gen(int count)
    {
        if (count <= 0) return;
        var aCount = World.instance.BlockCount("A");
        var bCount = World.instance.BlockCount("B");
        var cdCount = World.instance.BlockCount("C") + World.instance.BlockCount("D");
        var genB = false;
        if (cdCount >= higherCountForB) { genB = true; }
        if(bCount >= bThreshold) { genB = true; }

        var genlist = new string[count];
        for (int i = 0; i < count; i++)
        {
            if (genB && Random.value <= bChance) genlist[i] = "B";
            else genlist[i] = "A";
        }
        Enqueue(genlist);
    }
    #endregion
}
